package com.excesys.service.impl;

import cn.hutool.core.convert.Convert;
import com.excesys.entity.Goods;
import com.excesys.service.GoodsService;
import com.excesys.util.Tools;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class GoodsServiceImpl implements GoodsService {

    //格式化当当网数据
    @SneakyThrows
    public List parseDD(String key) {
        Map headers = new HashMap();
        headers.put("Proxy-Host", "www.duoip.cn"); // 设置代理主机
        headers.put("Proxy-Port", "8000"); // 设置代理端口
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"); // 伪装浏览器
        List list = new ArrayList();
        Document doc = Jsoup.connect("https://search.dangdang.com/?key=" + key + "").headers(headers).ignoreContentType(true).get();
        Elements els = doc.getElementById("search_nature_rg").getElementsByTag("li");
        for (int i = 0; i < els.size(); i++) {
            Elements children = els.get(i).children();
            String id = els.get(i).attr("id");
            String img = ObjectUtils.isEmpty(children.get(0).getElementsByTag("img").attr("data-original")) ? children.get(0).getElementsByTag("img").attr("src") : children.get(0).getElementsByTag("img").attr("data-original");
            String title = children.get(0).getElementsByTag("img").attr("alt").trim();
            String price = ObjectUtils.isEmpty(children.get(1).getElementsByClass("price_n").text()) ? els.get(i).getElementsByClass("search_now_price").text() : children.get(1).getElementsByClass("price_n").text();
            String store = children.get(5).getElementsByTag("a").attr("title");
            String search_hot_word = children.get(3).getElementsByClass("search_hot_word").text();
            list.add(new Goods(id, img, title, Convert.toDouble(Tools.getNumber(price)), store, search_hot_word));
        }
        list.forEach(item -> {
            log.info("爬取到数据:{}", item);
        });
        return list;
    }

}
